<template>
  <el-dialog
    :model-value="show"
    :title="dialogTitle"
    width="800px"
    append-to-body
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
  >
    <DynamicsForm
      ref="DynamicsFormRef"
      :api="formApi"
      :params="formParams"
      :form_uni_key="
        from === 'add' ? 'application_apply_create_form_company' : undefined
      "
    />
    <template #footer>
      <!-- 新增/重新填写 -->
      <el-button
        v-if="['add', 'edit'].includes(from)"
        type="primary"
        :loading="loading"
        :disabled="!show"
        @click="submitForm"
      >
        提交申请
      </el-button>
      <el-button type="info" @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import DynamicsForm from '@/components/DynamicsForm';
import {
  companyApplicationApply,
  companyApplicationReapply,
  companyApplicationForm_detail
} from '@/api/resources';

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  from: {
    type: String,
    default: '' // add 新增 edit 重新填写
  },
  activeRow: {
    type: Object,
    default: () => {}
  }
});
const emit = defineEmits(['success', 'update:show']);

const dialogTitle = computed(() => {
  return {
    add: '新增申请',
    edit: '重新填写申请'
  }[props.from];
});

const formApi = computed(() => {
  return {
    add: null,
    edit: companyApplicationForm_detail
  }[props.from];
});

const formParams = computed(() => {
  return {
    add: null,
    edit: { id: props.activeRow.id, view_type: 2 } // 2 重新申请
  }[props.from];
});

// 关闭
function handleClose() {
  emit('update:show', false);
}

// 提交
const DynamicsFormRef = ref();
const api = computed(() => {
  return {
    add: companyApplicationApply,
    edit: companyApplicationReapply
  }[props.from];
});
const loading = ref(false);
async function submitForm() {
  try {
    loading.value = true;
    const values = await DynamicsFormRef.value.returnData();
    api
      .value({ values })
      .then(() => {
        $msg.success('提交成功');
        emit('success', props.from === 'add' ? 'reset' : undefined);
        handleClose();
      })
      .finally(() => (loading.value = false));
  } catch {
    loading.value = false;
  }
}

// 初始化表单
watch(
  () => props.show,
  async val => {
    if (!val) return;
    await nextTick();
    DynamicsFormRef.value?.initFormList();
  }
);
</script>

<style lang="scss" scoped></style>
